<?php
namespace app\controller\back;

use app\common\controller\_AdminController;
use app\model\Role;
use app\model\Permission;
use app\model\Admin;
use think\Validate;

class RoleController extends _AdminController
{
	protected $rule = [
		'id|编号'            => 'integer',
		'name|名称'          => 'chsDash|length:2,50',
		'desc|描述'          => 'chsDash|max:200',
		'sort|排序'          => 'integer',
		'status|状态'        => 'in:0,1',
		'permission|路由'    => 'array|min:1',
		'page|分页'          => 'integer',
		'limit|条数'          => 'integer',
	];

	public $scene = [
		'create'		=>  ['name','desc','sort','status'],
		'update'		=>  ['id','name','desc','sort','status','permission'],
		'delete'		=>  ['id'],
		'list'  		=>  ['id','name','status','page','limit'],
		'detail'		=> 	['id'],
	];

	protected function initialize()
	{   
		parent::initialize();
		switch ($this->action) {
			case 'create':
				$this->appendRule('name','require|unique:role');
				break;
			case 'update':
				$this->appendRule('id','require|checkRoleById');
				$this->appendRule('name','unique:role');
				$this->appendRule('permission','checkPermission');
				break;
			case 'delete':
				$this->appendRule('id','require|checkRoleDel');
				break;
			case 'list':
				$this->appendRule('id','checkRoleById');
				$this->replaceRule('name','length:2,50','length:1,50');
				$this->replaceRule('status','in:0,1','in:0,1,2');
				break;
			case 'detail':
				$this->appendRule('id','require|checkRoleById');
				break;
			default:
				# code...
				break;
		}
		$this->check();
	}

	/**
	 * @api {POST} /back/role/create 添加角色
	 * @apiVersion 0.0.1
	 * @apiGroup Back-role
	 *
	 * @apiParam {String} name 名称
	 * @apiParam {String} [desc] 描述
	 * @apiParam {Number} [sort=0] 排序
	 * @apiParam {Number=0禁用,1启用} [status=1] 状态
	 *
	 * @apiParamExample {json} Request-Example:
	 * {
	 *     "name": "管理员管理",
	 *     "desc": "管理员管理",
	 *     "sort": "1",
	 *     "status": "1"
	 * }
	 *
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []   
	 * }
	 */
	public function createAction()
	{
		$error = Role::doSave($this->data);
		if($error){
			return parent::resError($error);
		}
		return parent::resSuccess();
	}

	/**
	 * @api {POST} /back/role/update 修改角色
	 * @apiVersion 0.0.1
	 * @apiGroup Back-role
	 *
	 * @apiParam {Number} id 编号
	 * @apiParam {String} [name] 名称
	 * @apiParam {String} [desc] 描述
	 * @apiParam {Number} [sort] 排序
	 * @apiParam {Number=0禁用,1启用} [status] 状态
	 * @apiParam {String[]} [permission] 权限数组
	 *
	 * @apiParamExample {json} Request-Example:
	 * {
	 *     "id": 1,
	 *     "name": "管理员管理",
	 *     "desc": "管理员管理",
	 *     "sort": "1",
	 *     "status": "1"
	 *     "permission[1]": "3",
	 *     "permission[2]": "5",
	 * }
	 * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []   
	 * }
	 */
	public function updateAction()
	{   
		$error = Role::doSave($this->data,$this->id);
		if($error){
			return parent::resError($error);
		}
		return parent::resSuccess();
	}

	/**
	 * @api {POST} /back/role/delete 删除角色
	 * @apiVersion 0.0.1
	 * @apiGroup Back-role
	 *
	 * @apiParam {Number} id 编号
	 *
	 * @apiParamExample {json} Request-Example:
	 * {
	 *     "id": 1,
	 * }
	 * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": []   
	 * }
	 */
	public function deleteAction()
	{   
		Role::doDelete($this->id);
        return parent::resSuccess();
	}

	/**
	 * @api {POST} /back/role/list 角色列表
	 * @apiVersion 0.0.1
	 * @apiGroup Back-role
	 *
	 * @apiParam {Number} [id] 编号
	 * @apiParam {String} [name] 名称
	 * @apiParam {Number=-1删除,0禁用,1启用,2禁用+启用} [status=2] 状态
	 * @apiParam {Number} [page=1] 页码
	 * @apiParam {Number} [limit=10] 每页条数
	 *
	 * @apiParamExample {json} Request-Example:
	 * {
	 *     "id": 1,
	 *     "name": "管理员管理",
	 *     "status": "1"
	 *     "page": "1",
	 *     "limit": "10",
	 * }
	 * 
	 * @apiSuccess {Number} id 编号
	 * @apiSuccess {String} name 名称
	 * @apiSuccess {String} desc 描述
	 * @apiSuccess {Number} sort 排序
	 * @apiSuccess {Number} status 状态码
	 * @apiSuccess {String} status_text 状态值
	 * @apiSuccess {Number} total 总条数
	 * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": {
	 *         "list": [
	 *             {
	 *                 "id": 1,
	 *                 "name": "管理员管理",
	 *                 "desc": "管理员管理",
	 *                 "sort": 0,
	 *                 "status": 1,
	 *                 "status_text": "正常"
	 *             },
	 *         ],
	 *         "total": 6
	 *     }
	 *}
	 */
	public function listAction()
	{   
		$cond = Role::getStatusCond($this->data);
        if( !empty($this->id) ){
            $cond[] = ['id','=',$this->id];
        }
        if(!empty($this->data['name'])){
            $cond[] = ['','exp',Role::raw("locate('{$this->data['name']}',name)>0")];
        }
		$list = Role::doList($cond,null);
		return parent::resSuccess($list);
	}

	/**
	 * @api {POST} /back/role/detail 角色详情
	 * @apiVersion 0.0.1
	 * @apiGroup Back-role
	 *
	 * @apiParam {Number} [id] 编号
	 *
	 * @apiParamExample {json} Request-Example:
	 * {
	 *     "id": 1,
	 * }
	 * 
	 * @apiSuccess {Number} id 编号
	 * @apiSuccess {String} name 名称
	 * @apiSuccess {String} desc 描述
	 * @apiSuccess {Number} sort 排序
	 * @apiSuccess {Number} status 状态码
	 * @apiSuccess {String} status_text 状态值
	 * @apiSuccess {Object[]} permission 权限数组
	 * @apiSuccess {Number} permission.id 编号
	 * @apiSuccess {String} permission.name 名称
	 * @apiSuccess {Number} permission.sort 排序
	 * @apiSuccess {Number} permission.status 状态码
	 * @apiSuccess {String} permission.status_text 状态值
	 * @apiSuccess {Object[]} permission.sub 权限数组
	 * @apiSuccess {Number} permission.sub.id 编号
	 * @apiSuccess {String} permission.sub.name 名称
	 * @apiSuccess {Number} permission.sub.group_id 分编号
	 * @apiSuccess {Number} permission.sub.status 状态码
	 * @apiSuccess {String} permission.sub.status_text 状态值
	 * @apiSuccess {String} permission.sub.path 路径
	 * @apiSuccess {String} permission.sub.desc 描述
	 * @apiSuccess {String} permission.sub.create_time 创建时间
	 * @apiSuccess {String} permission.sub.update_time 更新时间
	 * @apiSuccess {String} permission.sub.has 是否拥有
	 * 
	 * @apiSuccessExample {json} 成功返回:
	 * HTTP/1.1 200 OK
	 * {
	 *     "code":200,
	 *     "msg":"操作成功",
	 *     "data": {
     *         "id": 1,
     *         "name": "管理员管理1",
     *         "desc": "",
     *         "sort": 0,
     *         "permission": [
     *             {
     *                 "id": 1,
     *                 "name": "创建管理员",
     *                 "sort": 0,
     *                 "status": 1,
     *                 "status_text": "正常",
     *                 "sub": [
     *                     {
     *                         "id": 3,
     *                         "group_id": 1,
     *                         "name": "管理员管理1",
     *                         "path": "/back/admin/create1",
     *                         "desc": "123123",
     *                         "status": 1,
     *                         "create_time": "2019-05-16 15:34:50",
     *                         "update_time": "2019-05-16 15:34:50",
     *                         "has": 1,
     *                         "status_text": "正常"
     *                     }
     *                  ]
     *              }
     *          ]
	 *     }
	 * }
	 */
	public function detailAction()
	{   
		$list = Role::doDetail($this->id);
		return parent::resSuccess($list);
	}

	// 自定义规则
	protected function checkRoleById()
	{
		Validate::extend('checkRoleById', function ($value) {
			$role = Role::get($value);
			if(!$role){
				return '记录不存在';
			}
			return true;
		});
	}

	// 自定义验证规则
	protected function checkRoleDel()
	{
		Validate::extend('checkRoleDel', function ($value) {
			$role = Role::get($value);
			if(!$role){
				return '记录不存在';
			}
			if($role->status == role::STATUS_ENABLE){
				return '删除前请先禁用';
			}
			$sub = Admin::where(['role_id'=>$value])->find();
			if($sub){
				return '有下级数据,无法删除';
			} 
			return true;
		});
		
	}

	// 自定义规则
	protected function checkPermission()
	{
		Validate::extend('checkPermission', function ($value) {
			$cond[] = ['status','=',Permission::STATUS_ENABLE];
			$cond[] = ['pid','>',0];
			$permission = Permission::where($cond)->column('id');
			$diff = array_diff($value,$permission);
			if($diff){
				return '权限不存在或已被禁用';
			}
			return true;
		});
	}

}


